<?php

namespace youmbe\phpword\widgets;

use Yii;
use yii\helpers\ArrayHelper;
use PhpOffice\PhpWord\Style\TablePosition;
use yii\base\Arrayable;
use yii\base\InvalidConfigException;
use yii\base\Model;
use yii\helpers\Inflector;
use PhpOffice\PhpWord\Shared\Converter;

/**
 * The GridView widget is used to display data in a grid.
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class DirectionGridView extends GridView {

    const DIRECTION_VERTICAL = 'vertical';
    const DIRECTION_HORIZONTAL = 'horizontal';

    /**
     * @var string 列方向
     */
    public $direction = self::DIRECTION_HORIZONTAL;

    /**
     * @var array|string|null 单元格样式
     */
    public $cellStyle = [
        'borderColor' => '000000',
        'borderSize' => 2,
        'unit' => \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT,
    ];

    /**
     * Initializes the grid view.
     * This method will initialize required property values and instantiate [[columns]] objects.
     */
    public function init() {
        parent::init();
        if ($this->direction == static::DIRECTION_VERTICAL) {
            $this->showHeader = $this->showFooter = false;
        }
    }

    /**
     * Renders the table body.
     * @return string the rendering result.
     */
    public function renderTableBody() {
        if ($this->direction == static::DIRECTION_HORIZONTAL) {
            return parent::renderTableBody();
        }
        $models = array_values($this->dataProvider->getModels());
        $columnWidth = 100 / $this->dataProvider->getTotalCount();
        $rowStyle = $this->filterRowStyles($this->rowOptions);

        /* @var $column Column */
        foreach ($this->columns as $column) {
            $options = $column->contentOptions;
            $height = ArrayHelper::getValue($options, 'height');
            if ($height) {
                $height = Converter::pointToTwip($height);
            }
            $this->layout->addRow($height, $rowStyle);

            $fontStyle = $this->mergeStyleArray('fontStyle', $this->rowOptions, $options);
            if ($fontStyle) {
                $options['fontStyle'] = $fontStyle;
            }
            $paragraphStyle = $this->mergeStyleArray('paragraphStyle', $this->rowOptions, $options);
            if ($paragraphStyle) {
                $options['paragraphStyle'] = $paragraphStyle;
            }
            if ($columnWidth) {
                $options['width'] = $columnWidth;
            }
            $label = $column->renderHeaderCell();
            if ($label) {
                $label .= '：';
            }

            foreach ($models as $index => $model) {
                /* @var $column Column */
                $text = $column->renderDataCell($model, $index);
                $this->renderCell($this->layout, $label . $text, $options);
            }
        }
    }

}
